<template>
	<div class="system-menu-container layout-pd">
		<el-card shadow="hover">
			<div class="system-menu-search mb15">
				<el-row :gutter="20">
					<el-col :span="24">
						<el-input size="default" placeholder="系统模块查询" v-model="state.param.title" class="mt10"
							v-auth="'monitor:operlog:query'">
						</el-input>
						<el-input size="default" placeholder="操作人员查询" v-model="state.param.operName"
							v-auth="'monitor:operlog:query'" class="mt10"></el-input>
						<el-select size="default" v-model="state.param.businessType" placeholder="操作类型" clearable
							v-auth="'monitor:operlog:query'" class="mt10">
							<el-option v-for="dict in sys_oper_type" :key="dict.value" :label="dict.label"
								:value="dict.value" />
						</el-select>
						<el-select v-model="state.param.status" placeholder="操作状态" clearable size="default" class="mt10" v-auth="'monitor:operlog:query'">
							<el-option v-for="dict in sys_common_status" :key="dict.value" :label="dict.label"
								:value="dict.value" />
						</el-select>
						<el-form-item size="default" class="mt10" style="max-width: 250px;" v-auth="'monitor:operlog:query'">
							<el-date-picker v-model="state.dateRange" type="daterange" range-separator="至"
								start-placeholder="开始时间" end-placeholder="结束时间" />
						</el-form-item>
						<el-button size="default" type="primary" class="mt10" @click="getTableData" v-auth="'monitor:operlog:query'">
							<el-icon>
								<ele-Search />
							</el-icon>
							查询
						</el-button>
						<el-button size="default" class="mt10" type="info" @click="resetParamData()" v-auth="'monitor:operlog:query'">
							<el-icon>
								<ele-Refresh />
							</el-icon>
							重置
						</el-button>
						<el-button size="default" type="danger" class="mt10" @click="onBatchDelOperlog()" v-auth="'monitor:operlog:remove'">
							<el-icon>
								<ele-Delete />
							</el-icon>
							清空
						</el-button>
						<el-button size="default" type="warning" class="mt10" @click="onExportOperlog()" v-auth="'monitor:operlog:export'">
							<el-icon>
								<ele-Download />
							</el-icon>
							导出
						</el-button>
					</el-col>
				</el-row>
			</div>
			<el-table :data="state.tableData.data" v-loading="state.tableData.loading" style="width: 100%"
				ref="multipleTableRef" @selection-change="handleSelectionChange">
				<el-table-column type="selection" width="55" align="center" />
				<el-table-column label="日志编号" align="center" prop="operId" width="100" show-overflow-tooltip />
				<el-table-column label="系统模块" align="center" prop="title" width="100" />
				<el-table-column label="操作类型" align="center" prop="businessType">
					<template #default="scope">
						<dict-tag :options="sys_oper_type" :value="scope.row.businessType" />
					</template>
				</el-table-column>
				<el-table-column label="请求方式" align="center" prop="requestMethod" width="100" />
				<el-table-column label="操作人员" align="center" prop="operName" width="100" show-overflow-tooltip />
				<el-table-column label="操作地址" align="center" prop="operIp" width="130" show-overflow-tooltip />
				<el-table-column label="操作地点" align="center" prop="operLocation" show-overflow-tooltip />
				<el-table-column label="操作状态" align="center" prop="status">
					<template #default="scope">
						<dict-tag :options="sys_common_status" :value="scope.row.status" />
					</template>
				</el-table-column>
				<el-table-column label="操作日期" align="center" prop="operTime" width="180">
					<template #default="scope">
						<span>{{ scope.row.operTime }}</span>
					</template>
				</el-table-column>
				<el-table-column label="操作" show-overflow-tooltip width="140" fixed="right">
					<template #default="scope">
						<el-button link type="primary" @click="handleView(scope.row)"
							v-auth="'monitor:operlog:query'">详细</el-button>
						<el-button link type="danger" @click="onTabelRowDel(scope.row)"
							v-auth="'monitor:operlog:remove'">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
		</el-card>
		<el-pagination @size-change="onHandleSizeChange" @current-change="onHandleCurrentChange" class="mt15"
		:pager-count="5" :page-sizes="[10, 20, 30]" v-model:current-page="state.param.pageNum" background
		v-model:page-size="state.param.pageSize" layout="total, sizes, prev, pager, next, jumper"
		:total="state.total">
	</el-pagination>
		<OperlogDialog ref="operlogDialogRef" @refresh="getTableData()" />
	</div>
</template>

<script setup lang="ts" name="systemOperlog">
import { defineAsyncComponent, ref, reactive, onMounted } from 'vue';
import { ElMessageBox, ElMessage, dayjs, ElTable } from 'element-plus';
import { useOperlogApi } from '/@/api/monitor/operlog';
import { useDict } from '/@/utils/dict';
import { download, selectDictLabel } from '/@/utils/tool';
// 引入组件

const { sys_oper_type, sys_common_status } = useDict('sys_oper_type', 'sys_common_status');
const OperlogDialog = defineAsyncComponent(() => import('/@/views/monitor/operlog/dialog.vue'));

// 定义变量内容
const operlogDialogRef = ref();
const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const multipleSelection = ref<RowOperlogType[]>([])

const state = reactive<TableType>({
	dicts: ['sys_oper_type', 'sys_common_status'],
	tableData: {
		data: [],
		operlogOptions: [],
	},
	total: 0,
	loading: false,
	dateRange: [], // 时间范围
	param: {
		pageNum: 1,
		pageSize: 10,
		title: undefined,
		operName: undefined,
		businessType: undefined,
		status: undefined
	},
});

/**
 * 初始化表格数据
 * @returns
 */
const getTableData = async () => {
	state.tableData.loading = true;
	try {
		let param = {};
		if (state.dateRange && state.dateRange.length > 0) {
			param = {
				...state.param,
				'params[beginTime]': dayjs(state.dateRange[0]).format('YYYY-MM-DD'),
				'params[endTime]': dayjs(state.dateRange[1]).format('YYYY-MM-DD')
			};
		} else {
			param = { ...state.param };
		}
		const res = await useOperlogApi().list({
			...param,
		});
		state.tableData.data = res.rows;
		state.total = res.total;
	} catch (error) {
		Promise.reject(error);
	}
	state.tableData.loading = false;
};

/**
 * 多选
 */
const handleSelectionChange = (val: RowOperlogType[]) => {
	multipleSelection.value = val
}

/**
 * 导出日志
 */
const onExportOperlog = () => {
	download("monitor/operlog/export", {
		...state.param
	}, `config_${new Date().getTime()}.xlsx`);
};

/**
 * 打开查看日志弹窗
 * @param type
 * @param row 当前行数据
 */
const handleView = (row: RowOperlogType) => {
	operlogDialogRef.value.openDialog(row, selectDictLabel(sys_oper_type.value, row.businessType));
};

/**
 * 删除日志
 * @param row 当前行数据
 */
const onTabelRowDel = async (row: RowOperlogType) => {
	try {
		const confirmResult = await ElMessageBox.confirm(`此操作将永久删除日志标题：${row.title}, 是否继续?`, '提示', {
			confirmButtonText: '删除',
			cancelButtonText: '取消',
			type: 'warning',
		});
		if (confirmResult === 'confirm') {
			const response = await useOperlogApi().delOperlog(row.operId);
			ElMessage.success(response.msg);
			getTableData();
		} else {
			ElMessage.info('已取消删除');
		}
	} catch (error) {
		Promise.reject(error);
	}
};

/**
 * 清空日志
 */
const onBatchDelOperlog = async () => {
	try {
		await ElMessageBox.confirm(`此操作将清空当前页日志, 是否继续?`, '提示', {
			confirmButtonText: '删除',
			cancelButtonText: '取消',
			type: 'warning',
		}).then(() => {
			useOperlogApi().cleanOperlog().then((res) => {
				if (res.code === 200) {
					ElMessage.success(res.msg);
					getTableData();
				} else {
					ElMessage.error(res.msg);
				}
			});
		});
	} catch (error) {
		Promise.reject(error);
	}
};

/**
 * 重置查询日志
 */
const resetParamData = () => {
	state.dateRange = [];
	state.param = {
		pageNum: 1,
		pageSize: 10,
		operlogName: '',
		status: '',
	};
	getTableData();
};


// 分页改变
const onHandleSizeChange = (val: number) => {
	state.param.pageSize = val;
	getTableData();
};
// 分页改变
const onHandleCurrentChange = (val: number) => {
	state.param.pageNum = val;
	getTableData();
};

// 页面加载时
onMounted(() => {
	getTableData();
});

</script>
<style lang="scss" scoped>
.mt10 {
	max-width: 140px;
	margin: 10px 0 10px 10px;
}
</style>